package com.leetcode.LC_MED;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;

public class LC56_2 {
    private int[][] merge(int[][] intervals) {
        if (intervals==null||intervals.length==0){
            return new int[0][2];
        }
        int idx = -1;
        Arrays.sort(intervals, Comparator.comparingInt(v -> v[0]));
        int[][] res = new int[intervals.length][2];
        for (int[] interval : intervals) {
            if(idx==-1||interval[0]>res[idx][1]){
                res[++idx] = interval;
            }else {
                res[idx][1] = Math.max(interval[1], res[idx][1]);
            }
        }
        return Arrays.copyOf(res, idx+1);
    }

    public static void main(String[] args) {
        LC56_2 lc56_2 = new LC56_2();
        int[][] merge = lc56_2.merge(new int[][]{{1, 3}, {2, 6}, {6, 10}, {15, 18}});
        for (int[] ints : merge) {
            for (int anInt : ints) {
                System.out.print(anInt+",");
            }
            System.out.println();
        }
    }
}
